import wepy from 'wepy'

export default class extends wepy.mixin {
  data = {
    goodsList: [],
    query: "",
    cid: "",
    pagenum: 1,
    pagesize: 10,
    total: 0,
    isover: false,
    isloading: false
  }

  methods = {
    goGoods_main(id) {
      wepy.navigateTo({
        url: '/pages/goods_detail/main?goods_id=' + id
      })
    }
  }

  onLoad(options) {
    //console.log(options)
    this.query = options.query || '';
    this.cid = options.cid || '';
    this.getGoodsList()
  }

  // 获取商品列表数据
  async getGoodsList(cb) {
    this.isloading = true
    var { data: res } = await wepy.get('/goods/search', {
      query: this.query,
      cid: this.cid,
      pagenum: this.pagenum,
      pagesize: this.pagesize
    })
    if (res.meta.status != 200)
      return wepy.baseToast();
    this.goodsList = [...this.goodsList, ...res.message.goods]
    this.total = res.message.total
    this.$apply()
    this.isloading = false
        cb && cb()
  }

  // 上拉加载事件
  onReachBottom() {
    if (this.isloading) return
    //console.log(this.allpagenum)
    if ((this.pagenum * this.pagesize) >= this.total) return this.isover = true;
    this.pagenum++;
    this.getGoodsList();
  }
  // 下拉刷新事件
  onPullDownRefresh() {
    // 初始化必要的字段
    this.pagenum = 1,
      this.total = 0,
      this.isover = false,
      this.isloading = false,
      this.goodsList = []
    // 方法一： 传回调函数
    this.getGoodsList(function(){
      wepy.stopPullDownRefresh()
    })
    // 方法二  
    // this.getGoodsList().then(() => wepy.stopPullDownRefresh())
  }

}